﻿using GalaSoft.MvvmLight;
using Microsoft.Practices.ServiceLocation;
using MyToolkit.Multimedia;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Media;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;
using Youtube_HD.Model;
using Youtube_HD.Services;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkID=390556

namespace Youtube_HD.View
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>


    public sealed partial class DetailPage : Page
    {
        SystemMediaTransportControls systemMediaControls = null;
        YoutubeVideo playItem = null;

        public DetailPage()
        {
            this.InitializeComponent();
            this.Loaded += DetailPage_Loaded;
            this.NavigationCacheMode = NavigationCacheMode.Required;
        }
        private IHomeViewModel homeViewModel
        {
            get { return ServiceLocator.Current.GetInstance<IHomeViewModel>(); }
        }
        IPlayListViewModel playListViewModel
        {
            get { return ServiceLocator.Current.GetInstance<IPlayListViewModel>(); }
        }
        async void DetailPage_Loaded(object sender, RoutedEventArgs e)
        {
            DetailsData.DataContext = playItem;
            playListViewModel.YoutubeVideosListRelated = null;
            Scenario6MediaElement.Source = null;
            loadData.IsActive = true;
            playListViewModel.GetListReletedPlayList(playItem.Id);

            YouTubeUri getVideos = await homeViewModel.GetVideoUriAsync(playItem.Id, MyToolkit.Multimedia.YouTubeQuality.QualityHigh);
            if (getVideos != null)
            {
                Scenario6MediaElement.Source = getVideos.Uri;
            }
            else
            {
                new MessageDialog("load video failed!").ShowAsync();
            }
            loadData.IsActive = false;
        }

        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            playItem = (YoutubeVideo)e.Parameter;
          
            // Handle events from system transport contrtols when playing background-capable media
            systemMediaControls = SystemMediaTransportControls.GetForCurrentView();
            systemMediaControls.ButtonPressed += SystemMediaControls_ButtonPressed;
            systemMediaControls.IsPlayEnabled = true;
            systemMediaControls.IsPauseEnabled = true;
            systemMediaControls.IsStopEnabled = true;
            systemMediaControls.IsPreviousEnabled = true;
            systemMediaControls.IsRecordEnabled = true;
            systemMediaControls.IsRewindEnabled = true;
            systemMediaControls.IsFastForwardEnabled = true;
            Scenario6MediaElement.CurrentStateChanged += MediaElement_CurrentStateChanged;
        }
        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            if (systemMediaControls != null)
            {
                systemMediaControls.ButtonPressed -= SystemMediaControls_ButtonPressed;
                systemMediaControls.IsPlayEnabled = false;
                systemMediaControls.IsPauseEnabled = false;
                systemMediaControls.IsStopEnabled = false;
                systemMediaControls.PlaybackStatus = MediaPlaybackStatus.Closed;
                systemMediaControls.DisplayUpdater.ClearAll();
                systemMediaControls.DisplayUpdater.Update();
                systemMediaControls = null;
            }

            Scenario6MediaElement.Source = null;
        }
        /// <summary>
        /// Handler for the system transport controls button.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void SystemMediaControls_ButtonPressed(SystemMediaTransportControls sender, SystemMediaTransportControlsButtonPressedEventArgs e)
        {
            switch (e.Button)
            {
                case SystemMediaTransportControlsButton.Play:
                    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        Scenario6MediaElement.Play();
                    });
                    break;

                case SystemMediaTransportControlsButton.Pause:
                    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        Scenario6MediaElement.Pause();
                    });
                    break;

                case SystemMediaTransportControlsButton.Stop:
                    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        Scenario6MediaElement.Stop();
                    });
                    break;

                default:
                    break;
            }
        }

        /// <summary>
        /// Handler for the media element state change
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MediaElement_CurrentStateChanged(object sender, RoutedEventArgs e)
        {
            SystemMediaTransportControls systemMediaControls = SystemMediaTransportControls.GetForCurrentView();
            switch (Scenario6MediaElement.CurrentState)
            {
                default:
                case MediaElementState.Closed:
                    systemMediaControls.PlaybackStatus = MediaPlaybackStatus.Closed;
                    break;

                case MediaElementState.Opening:
                    systemMediaControls.PlaybackStatus = MediaPlaybackStatus.Changing;
                    break;

                case MediaElementState.Buffering:
                case MediaElementState.Playing:
                    systemMediaControls.PlaybackStatus = MediaPlaybackStatus.Playing;
                    break;

                case MediaElementState.Paused:
                    systemMediaControls.PlaybackStatus = MediaPlaybackStatus.Paused;
                    break;

                case MediaElementState.Stopped:
                    systemMediaControls.PlaybackStatus = MediaPlaybackStatus.Stopped;
                    break;
            }
        }

        private async void Videos_ItemClick(object sender, ItemClickEventArgs e)
        {
            var getDat = (YoutubeVideo)e.ClickedItem;
            Scenario6MediaElement.Stop();
            Scenario6MediaElement.Source = null;
            loadData.IsActive = true;
            playListViewModel.YoutubeVideosListRelated = null;
            playListViewModel.GetListReletedPlayList(playItem.Id);
            DetailsData.DataContext = playItem;
            YouTubeUri getVideos = await homeViewModel.GetVideoUriAsync(getDat.Id, MyToolkit.Multimedia.YouTubeQuality.QualityHigh);
            if (getVideos != null)
            {
                Scenario6MediaElement.Source = getVideos.Uri;
               
            }
            else
            {
                new MessageDialog("load video failed!").ShowAsync();
            }
            loadData.IsActive = false;

        }

    }
}
